package com.chuanjiabao.wisdom.application;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.chuanjiabao.wisdom.BuildConfig;
import com.chuanjiabao.wisdom.greendao.gen.DaoMaster;
import com.chuanjiabao.wisdom.greendao.gen.DaoSession;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.utils.OkLogger;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;

import java.util.Map;
import java.util.logging.Level;

import me.leolin.shortcutbadger.ShortcutBadger;
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;
import tv.danmaku.ijk.media.player.PlayerFactory;
import tv.danmaku.ijk.media.utils.VideoType;

import static com.chuanjiabao.wisdom.bean.Constants.WX_PAY_APPID;
import static com.chuanjiabao.wisdom.bean.Constants.WX_PAY_SECRET;

public class FApplication extends Application {

    public static FApplication instance;
    public static int badgeNumber = 0;

    public static FApplication getInstance() {
        return instance;
    }

    private String mDeviceToken;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        //log日志
        LogUtil.init(BuildConfig.DEBUG);

        OkGo.init(this);
        OkGo.getInstance().debug("OkGo", Level.INFO, BuildConfig.DEBUG);

        VideoType.enableMediaCodec();
        VideoType.enableMediaCodecTexture();
        PlayerFactory.setPlayManager(Exo2PlayerManager.class);

        //友盟统一初始化
        UMConfigure.init(
                this,
                "5dca643f570df3c20a000871",
                "Umeng",
                UMConfigure.DEVICE_TYPE_PHONE,
                "fb2da82d1737e3b79c351fbcfcac196d"
        );

        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                mDeviceToken = deviceToken;
                OkLogger.i("UMPush", "注册成功：deviceToken：" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                OkLogger.e("UMPush", "注册失败：s:" + s + ",s1:" + s1);
            }
        });

        HuaWeiRegister.register(this);
        MiPushRegistar.register(this, "2882303761518246452", "5591824683452");
        OppoRegister.register(this, "5499be84631a415f9e6f9d4a60230d65", "acc12dcd75904586ad7b99009d1f1dd8");
        VivoRegister.register(this);

        mPushAgent.setMessageHandler(new UmengMessageHandler() {
            @Override
            public Notification getNotification(Context context, UMessage uMessage) {
                Map<String, String> extra = uMessage.extra;
                if (extra != null) {
                    String strNum = extra.get("badge_num");
                    if (TextUtils.isEmpty(strNum)) {
                        badgeNumber += 1;
                        checkBadgeNum(context, badgeNumber);
                    } else {
                        badgeNumber += Integer.parseInt(strNum);
                        checkBadgeNum(context, badgeNumber);
                    }
                } else {
                    badgeNumber += 1;
                    checkBadgeNum(context, badgeNumber);
                }

                Notification notification = super.getNotification(context, uMessage);
                ShortcutBadger.applyNotification(context, notification, badgeNumber);

                return notification;
            }
        });

        //友盟分享
        PlatformConfig.setWeixin(WX_PAY_APPID, WX_PAY_SECRET);
        PlatformConfig.setQQZone("1110084282", "X7bx5fyj83SilCIs");
        Config.isJumptoAppStore = true;
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);

        setDatabase();
    }

    public String getDeviceToken() {
        return mDeviceToken;
    }

    private void checkBadgeNum(Context context, int num) {
        String osName = StringUtil.getOSName();
        switch (osName) {
            case "huawei":
                if (!StringUtil.isAppForeground(context, "com.chuanjiabao.wisdom")) {
                    ShortcutBadger.applyCount(context, num);
                }
                break;
            case "xiaomi":
                break;
            default:
                if (!StringUtil.isAppForeground(context, "com.chuanjiabao.wisdom")) {
                    ShortcutBadger.applyCount(context, num);
                }
                break;
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public ClientConfiguration getClientConfiguration() {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000);
        conf.setSocketTimeout(15 * 1000);
        conf.setMaxConcurrentRequest(5);
        conf.setMaxErrorRetry(2);
        return conf;
    }

    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    private void setDatabase() {
        mHelper = new DaoMaster.DevOpenHelper(this, "wisdom_db", null);
        db = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

}
